package pers.sun.oauthclient.servlet;

import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import pers.sun.oauthclient.util.OAuthClientUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by lenovo on 2016/5/18.
 */
public class ResourceServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OAuthClientUtil oAuthClientUtil = new OAuthClientUtil("testclient","clientsecret","http://localhost:8080/OAuthClient/oauth/Resource");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        //接收国家平台返回的code,进而进行token获取，最终获得用户信息
        String code = req.getParameter("code");
        String state = req.getParameter("state");

        ServletContext servletContext = this.getServletContext();
        if (state.equals(servletContext.getAttribute("state"))) {
            oAuthClientUtil.setState(state);
            try {
                String token = oAuthClientUtil.TokenTest(code);
                String userinfo = oAuthClientUtil.ResourceTest(token);
                PrintWriter writer = resp.getWriter();
                writer.println("<p>1.后台获得用户数据:</p><br/>");
                writer.println("<p style = 'color:blue;' >" + userinfo + "</p>");
                writer.println("<br/>");
                writer.println("<p>2.根据返回的nickname查询是否有与本平台绑定的账号。</p><br/>");
                writer.println("<p>3.如果有绑定的账号，则登录此账号，然后跳转到用户预约的仪器的预约页面。</p><br/>");
                writer.println("<p>4.如果没有绑定的账号，则转到注册页面，可以使用返回的信息方便用户的注册过程，然后注册并绑定国家平台账号后，跳转到预约页面。</p><br/>");
            } catch (OAuthSystemException e) {
                e.printStackTrace();
            } catch (OAuthProblemException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
